package cluster

import (
	"github.com/rs/zerolog/log"
	apiv1a1 "gomod.alauda.cn/mysql-mgr-operator/api/v1alpha1"
	"gomod.alauda.cn/rds-operator/api/external/mgr"
	rdsv1 "gomod.alauda.cn/rds-operator/api/v1"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	"k8s.io/apimachinery/pkg/util/json"
	"k8s.io/utils/pointer"
)

var defaultCluster *apiv1a1.MySQLCluster
var defaultMysql *rdsv1.Mysql

func init() {
	initMgr()
	initMysql()
}

func initMgr() {
	res := &corev1.ResourceRequirements{
		Requests: map[corev1.ResourceName]resource.Quantity{
			corev1.ResourceCPU:    resource.MustParse("1"),
			corev1.ResourceMemory: resource.MustParse("1Gi"),
		},
		Limits: map[corev1.ResourceName]resource.Quantity{
			corev1.ResourceCPU:    resource.MustParse("1"),
			corev1.ResourceMemory: resource.MustParse("1Gi"),
		},
	}
	defaultCluster = &apiv1a1.MySQLCluster{
		Spec: apiv1a1.MySQLClusterSpec{
			Version:       "8.0",
			Members:       3,
			EnableStorage: true,
			VolumeClaimTemplate: &corev1.PersistentVolumeClaim{
				Spec: corev1.PersistentVolumeClaimSpec{
					StorageClassName: pointer.String("sc-topolvm"),
					Resources: corev1.ResourceRequirements{
						Requests: map[corev1.ResourceName]resource.Quantity{
							corev1.ResourceStorage: resource.MustParse("1Gi"),
						},
					},
				},
			},
			Resources: &apiv1a1.Resources{
				//Agent:  res,
				Server: res,
			},
			Router: apiv1a1.MySQLRouter{
				Replicas:  1,
				Resources: res,
			},
			Monitor: &apiv1a1.Monitor{
				Enable: true,
			},
		},
	}
}

func initMysql() {
	defaultMysql = BuildMysql(defaultCluster)
}

func BuildMysql(clusterCr *apiv1a1.MySQLCluster) *rdsv1.Mysql {
	marshal, err := json.Marshal(clusterCr.Spec.DeepCopy())
	if err != nil {
		log.Fatal().Err(err).Msg("init mysql template fatal")
		return nil
	}
	mgrSpec := new(mgr.ClusterSpec)
	err = json.Unmarshal(marshal, mgrSpec)
	if err != nil {
		log.Fatal().Err(err).Msg("init mysql template fatal")
		return nil
	}
	mgrSpec.Version = ""
	mysqlCr := &rdsv1.Mysql{
		ObjectMeta: clusterCr.ObjectMeta,
		Spec: rdsv1.MysqlSpec{
			Version: "8.0",
			MGR:     mgrSpec,
		},
	}
	return mysqlCr
}
